package com.syq.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取方法名
        String methodName = request.getParameter("method");
        //反射
        try {
            Method method = this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //反射调用
            String url= (String) method.invoke(this,request,response);
            if (url!=null&&url.trim().length()!=0){
                //转发或重定向
                if (url.startsWith("redirect:")){
                    url=url.substring(url.indexOf(":")+1);
                    response.sendRedirect(request.getContextPath()+url);
                }else {
                    request.getRequestDispatcher(url).forward(request,response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
